package com.alipay.service.imp;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.alipay.service.AlipayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
@Service
public class AlipayServiceImpl implements AlipayService {
    Logger log = LoggerFactory.getLogger(AlipayServiceImpl.class);
    @Value("${alipay.returnUrl}")
    private String returnUrl;
    /**
     * web端订单支付 下单
     * @param outTradeNo 订单编号（唯一）
     * @param totalAmount 订单价格
     * @param subject 商品名称
     */
    @Override
    public String webPagePay(String outTradeNo, String totalAmount, String
            subject) throws Exception {
        AlipayTradePagePayResponse response =
                Factory.Payment.Page().pay(subject, outTradeNo, totalAmount, returnUrl);
        if (ResponseChecker.success(response)){
            log.info("调用成功");
            return response.getBody();
        }else {
            log.error("调用失败 原因是"+response.getBody());
        }
        return null;
    }
    /**
     * 支付异步回调
     * 将异步通知中收到的所有参数都存放到map中
     * 接收异步通知中返回的参数（支付宝服务器返回给商户服务器的通知，需要进行验签操作，验证支付
     是否真的成功）
     * @param request
     * @return
     * "trade_status"
     * "TRADE_SUCCESS"
     */
    @Override
    public String notifyUrl(HttpServletRequest request) throws Exception {
//1.创建map集合对象 接收异步通知返回的参数
        HashMap<String, String> map = new HashMap<>();
//2.获取所有的参数名称
        Enumeration<String> parameterNames = request.getParameterNames();
//3.遍历
        while (parameterNames.hasMoreElements()){
            String key = parameterNames.nextElement();
// 获取key对应的参数
            String value = request.getParameter(key);
            map.put(key,value);
        }
//使用支付宝支付工厂校验
        if (Factory.Payment.Common().verifyNotify(map)){
            log.info("异步通知验签通过");
// 验证支付是否真正成功
            String trade_status = request.getParameter("trade_status");
            if (trade_status.equals("TRADE_SUCCESS")){
                log.info("支付交易成功");
            }
        }else {
            log.error("异步通知验签失败");
            return "fail";
        }
        return "success";
    }
    /**
     * 支付同步步回调
     * @param request
     * @return
     */
    @Override
    public Map<String, String[]> returnUrl(HttpServletRequest request) {
        return request.getParameterMap();
    }
}